package com.molyfun.parents.fragment.dialog;

import android.os.Bundle;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.molyfun.parents.MFPApplication;
import com.molyfun.parents.R;
import com.molyfun.parents.fragment.BaseDialogFragment;
import com.molyfun.parents.rest.BaseResponse;
import com.molyfun.parents.rest.bean.StringResponse;
import com.molyfun.parents.utils.IDCardValidate;
import com.molyfun.parents.utils.PreferencesStorageUtil;
import com.molyfun.parents.utils.TimeUtils;
import com.molyfun.parents.utils.UIUtils;
import com.molyfun.parents.view.SexChooseView;
import com.molyfun.parents.view.common.MfEditText;

import butterknife.ButterKnife;
import butterknife.InjectView;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class OrigiationApplyFragment extends BaseDialogFragment implements View.OnClickListener, TextWatcher {

    private static final int ORGANIZATION_CODE_LENTH = 8;

    @InjectView(R.id.organization_code)
    MfEditText mOrigiationCode;
    @InjectView(R.id.organization_verify_layout)
    LinearLayout mOrganizationVerifyLayout;
    @InjectView(R.id.organization_verify_img)
    ImageView mVerifyImg;
    @InjectView(R.id.organization_name)
    TextView mOrganizationName;
    @InjectView(R.id.card_num)
    MfEditText mUserCardNum;
    @InjectView(R.id.organization_user_name)
    MfEditText mOrigiationUserName;
    @InjectView(R.id.birthday_choose)
    TextView mBirthdayChoose;
    @InjectView(R.id.sex_choose_view)
    SexChooseView mSexChooseView;
    @InjectView(R.id.cancel)
    TextView mCancel;
    @InjectView(R.id.commit)
    TextView mCommit;

    private String mChooseDate;

    private static OrigiationApplyFragment newInstance() {
        OrigiationApplyFragment mStudentMenuDialogFragment = new OrigiationApplyFragment();
//        Bundle bundle = new Bundle();
//        mStudentMenuDialogFragment.setArguments(bundle);
        return mStudentMenuDialogFragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.setCancelable(false);
//        setStyle(DialogFragment.STYLE_NORMAL, R.style.BaseDialog);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        getDialog().requestWindowFeature(Window.FEATURE_NO_TITLE);
        View view = inflater.inflate(R.layout.dialog_origiation_apply, container, false);
        ButterKnife.inject(this, view);
        mCancel.setOnClickListener(this);
        mCommit.setOnClickListener(this);
        mOrigiationCode.addTextChangedListener(this);
        if (!PreferencesStorageUtil.isUserEnter(getContext())) {
            mBirthdayChoose.setOnClickListener(this);
        } else {
            if (!TextUtils.isEmpty(MFPApplication.getInstance().getUser().getStudentname())) {
                mOrigiationUserName.setText(MFPApplication.getInstance().getUser().getStudentname());
                mOrigiationUserName.setEnabled(false);
            }
            if (MFPApplication.getInstance().getUser().getStudentbirthdatetime() != 0l) {
                mBirthdayChoose.setText(TimeUtils.getDateByTimeMillis(MFPApplication.getInstance().getUser().getStudentbirthdatetime()));
            } else {
                mBirthdayChoose.setOnClickListener(this);
            }
            if (!TextUtils.isEmpty(MFPApplication.getInstance().getUser().getCardid())) {
                mUserCardNum.setText(MFPApplication.getInstance().getUser().getCardid());
                mUserCardNum.setEnabled(false);
            }
            mSexChooseView.setCurrentSex(MFPApplication.getInstance().getUser().getStudentsex());

        }

        return view;
    }

    private String mUserCardNumStr;

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.cancel:
                getDialog().dismiss();
                break;
            case R.id.commit:
                if (!mIsOrganizationVerify) {
                    UIUtils.showToast(getContext(), "请输入正确的机构代码");
                    return;
                }
                if (TextUtils.isEmpty(mOrigiationUserName.getText().toString().trim())) {
                    UIUtils.showToast(getContext(), "请输入学生姓名");
                    return;
                }
                if (TextUtils.isEmpty(mBirthdayChoose.getText().toString().trim())) {
                    UIUtils.showToast(getContext(), "请输入学生出生日期");
                    return;
                }
                if (!TextUtils.isEmpty(mUserCardNum.getText().toString().trim())) {

                    IDCardValidate.validate_effective(mUserCardNum.getText().toString().trim(), new IDCardValidate.CardValidateCallback() {
                        @Override
                        public void onSuccess(String cardNum) {
                            mUserCardNumStr = cardNum;
                        }

                        @Override
                        public void onError(String cardErrorMsg) {
                            mUserCardNumStr = null;
                            UIUtils.showToast(getContext(), cardErrorMsg);
                        }
                    });
                    if (TextUtils.isEmpty(mUserCardNumStr)) {
                        return;
                    }
                }
                bingOrganization(mOrigiationCode.getText().toString().trim(), mOrigiationUserName.getText().toString().trim(), mBirthdayChoose.getText().toString(), mSexChooseView.getCurrentSex(), mUserCardNumStr);

                break;
            case R.id.birthday_choose:

                TimeUtils.getChooseDate(getContext(), new DatePickerDialogFragment.IDateCallback() {
                    @Override
                    public void onTimeChoosed(String time) {
                        mChooseDate = time;
                        mBirthdayChoose.setText(time);

                    }
                });

                break;
            default:
                break;
        }

    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {

    }

    @Override
    public void afterTextChanged(Editable s) {
        if (s.length() >= ORGANIZATION_CODE_LENTH) {
            checkOrganization(s.toString().trim());
        } else {
            mIsOrganizationVerify = false;
            mOrganizationVerifyLayout.setVisibility(View.GONE);
        }
    }

    private boolean mIsOrganizationVerify = false;

    private void checkOrganization(String organizationCode) {
        Call<StringResponse> call = MFPApplication.getInstance().getRestClient().checkOrganization(organizationCode);
        call.enqueue(new Callback<StringResponse>() {
            @Override
            public void onResponse(Call<StringResponse> call, Response<StringResponse> response) {
                if (response.body() != null) {
                    mOrganizationVerifyLayout.setVisibility(View.VISIBLE);
                    if (response.body().getCode() == 200) {
                        mIsOrganizationVerify = true;
                        mVerifyImg.setImageResource(R.mipmap.ic_origiation_right);
                        mOrganizationName.setText(response.body().getData());
                    } else {
                        mIsOrganizationVerify = false;
                        mVerifyImg.setImageResource(R.mipmap.ic_origiation_wrong);
                        mOrganizationName.setText("机构代码错误");
                    }

                }
            }

            @Override
            public void onFailure(Call<StringResponse> call, Throwable t) {
                mVerifyImg.setImageResource(R.mipmap.ic_origiation_wrong);
                mOrganizationName.setText("网络出错");
                mIsOrganizationVerify = false;
            }
        });
    }

    private void bingOrganization(String organizationCode, String studentName, String birthdatetime, String sex, String cardId) {
        showProgressDialog();
        Call<BaseResponse> call = MFPApplication.getInstance().getRestClient().bindOrganization(organizationCode, "org", studentName,
                birthdatetime, sex, cardId);
        call.enqueue(new Callback<BaseResponse>() {
            @Override
            public void onResponse(Call<BaseResponse> call, Response<BaseResponse> response) {
                if (response.body() != null) {
                    if (response.body().getCode() == 200) {
                        if (getContext() != null) {
                            UIUtils.showToast(getContext(), "申请成功");
                            if (mFragmentManager != null) {
                                new OrigiationApplySuccessFragment.OrigiationApplySuccessDialogBuilder()
                                        .build(mFragmentManager.beginTransaction());
                            }
                            dismissProgressDialog();
                            getDialog().dismiss();
                        }
                    } else {
                        dismissProgressDialog();
                        UIUtils.showToast(getContext(), response.body().getMsg());
                    }
                } else {
                    dismissProgressDialog();
                    UIUtils.showToast(getContext(), "申请出错");
                }
            }

            @Override
            public void onFailure(Call<BaseResponse> call, Throwable t) {
                dismissProgressDialog();
                UIUtils.showToast(getContext(), "申请出错");
            }
        });
    }

    private FragmentManager mFragmentManager;

    public void setFragmentManager(FragmentManager fragmentManager) {
        this.mFragmentManager = fragmentManager;
    }


    public static class OrigiationApplyDialogBuilder {

        OrigiationApplyFragment mCommonDialogFragment;
        private String mTag;

        public OrigiationApplyDialogBuilder() {
            mCommonDialogFragment = OrigiationApplyFragment.newInstance();
            mTag = "origiation_apply";
        }

        public OrigiationApplyDialogBuilder setTag(String tag) {
            this.mTag = tag;
            return this;
        }

        public void build(FragmentManager fragmentManager) {
            mCommonDialogFragment.setFragmentManager(fragmentManager);
            FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
            fragmentTransaction.add(mCommonDialogFragment, mTag);
            fragmentTransaction.commitAllowingStateLoss();
        }

    }
}
